package com.lengyu.iottransfer.gateway.controller;


import com.alibaba.fastjson.JSONObject;
import com.lengyu.iottransfer.gateway.common.ByteUtils;
import com.lengyu.iottransfer.gateway.common.HttpRequestUtil;
import com.lengyu.iottransfer.gateway.common.HttpResultDto;
import com.lengyu.iottransfer.gateway.config.MqttSendGateway;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liuyu
 * @since 2023-01-29
 */
@RestController
@RequestMapping("/test")
public class TestController {
    private final static Logger logger = LoggerFactory.getLogger(TestController.class);
    @Resource
    private MqttSendGateway mqttSendGateway;

    @PostMapping(value="/getmqtt-connect-info")
    public HttpResultDto<JSONObject> getMqttInfo(){
        String clientId = "mqtt-test";
        String secureId = "tjgk_secureId";
        String secureKey="tjgk_secureKey";
        long timestamp = System.currentTimeMillis();
        StringBuilder username = new StringBuilder();
        StringBuilder password = new StringBuilder();
        username.append(secureId).append("|").append(timestamp);
        password.append(secureId).append("|").append(timestamp).append("|").append(secureKey);
        String passwordMd5 = DigestUtils.md5DigestAsHex(password.toString().getBytes(StandardCharsets.UTF_8));
        JSONObject json = new JSONObject();
        json.put("clientId",clientId);
        json.put("username",username);
        json.put("password",passwordMd5);

        return HttpResultDto.success(json);
    }

    @PostMapping(value="/send_mqtt_message")
    public HttpResultDto<String> getMqttBroker(@RequestBody JSONObject json){
        String data = "01 03 00 03 00 03 ";
        if(json.containsKey("HexData")){
            data = json.getString("HexData");
        }

        String HexStr =  ByteUtils.getCRC16(data,true);
        mqttSendGateway.sendToMqtt("topic1", ByteUtils.hexStrToByteArray(data + HexStr));
        logger.info(HexStr);
        return HttpResultDto.success(HexStr);
    }






}
